package com.gionee.navil.lockscreen;

import java.util.List;

import com.android.internal.widget.LockPatternUtils;

import android.app.ActivityOptions;
import android.appwidget.AppWidgetHost;
import android.appwidget.AppWidgetHostView;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.os.Bundle;
import android.os.Looper;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RemoteViews.OnClickHandler;

public class GnNavilLockScreen extends GnKeyguardWidgetFrame implements GnKeyguardScreen {
	private final String PKN = "com.gionee.weibowidget";
	private final String CLS = "com.gionee.weibowidget.WeiboWidgetProviderMulti";

	private final static boolean ENABLE_ADD_WIDGET = false;
	private final int MAX_WIDGETS = 5;
	private static final int APPWIDGET_HOST_ID = 0x4B455947;
	private static final String TAG = "MainActivity";
	private GnLockScreenUtils mLockScreenUtils;
	private AppWidgetManager mAppWidgetManager;
	private AppWidgetHost mAppWidgetHost;
	private GnKeyguardWidgetPager mAppWidgetContainer;
	private int mIndex = 0;
	private View mAddWidget;
	private boolean mIsShowAddWiget = true;

	public GnNavilLockScreen(Context context) {
		this(context, null);
	}

	public GnNavilLockScreen(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public GnNavilLockScreen(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		LayoutInflater inflater = LayoutInflater.from(context);
		View view = inflater.inflate(
				R.layout.zzzzz_gn_navil_ly_main, this, true);
		
		mLockScreenUtils = new GnLockScreenUtils(mContext);
		mAppWidgetManager = AppWidgetManager.getInstance(mContext);

		List<AppWidgetProviderInfo> list = mAppWidgetManager
				.getInstalledProviders();
		if (list != null) {
			for (AppWidgetProviderInfo info : list) {
				GnLog.d("widgets", info.toString() + ",title=" + info.label);
			}
		}

		mAppWidgetHost = new AppWidgetHost(mContext, APPWIDGET_HOST_ID,
				mOnClickHandler, Looper.myLooper());
		
		View deleteDropTarget = view.findViewById(R.id.zzzzz_gn_navil_id_keyguard_widget_pager_delete_target);
		mAppWidgetContainer = (GnKeyguardWidgetPager) view.findViewById(R.id.zzzzz_gn_navil_id_app_widget_container);
		mAppWidgetContainer.setDeleteDropTarget(deleteDropTarget);
		mAppWidgetContainer.setMinScale(0.5f);
		mAppWidgetContainer.setCallbacks(mWidgetCallbacks);
		mAppWidgetContainer.setLockPatternUtils(mLockScreenUtils);
		mAppWidgetContainer.showInitialPageHints();
		GnNavilIndicator2 indicatot = (GnNavilIndicator2) view.findViewById(R.id.zzzzz_gn_navil_indicator);

		if (ENABLE_ADD_WIDGET) {
			addDefaultWidgets();
		}
		addWidgetsFromSettings();
		addLeftPage();
		addHomePage();
		addRightpage();

		if (ENABLE_ADD_WIDGET && numWidgets() >= MAX_WIDGETS) {
			mAppWidgetContainer.removeViewAt(0);
			mIsShowAddWiget = false;
		}
		mAppWidgetContainer.setCurrentPage(1);
		if (mAppWidgetContainer.getChildCount() > 0) {
			indicatot.setVisibility(View.VISIBLE);
			mAppWidgetContainer.setIndicator(indicatot);
		}
		
	}

	private void addWidgetsFromSettings() {

		// Add user-selected widget
		final int[] widgets = mLockScreenUtils.getAppWidgets();
		int insertionIndex = getInsertPageIndex();

		if (widgets == null) {
			GnLog.d(TAG, "Problem reading widgets");
		} else {
			int lenght = widgets.length;
			if (lenght == 0) {
				int id1 = allocateIdForDefaultAppWidget(PKN, CLS);
				if (id1 > 0) {
					mLockScreenUtils.addAppWidget(id1, 0);
					addWidget(id1, insertionIndex, true);
				}
				int id2 = allocateIdForDefaultAppWidget("com.android.music",
						"com.android.music.LargerAppWidgetProvider");

				if (id2 > 0) {
					mLockScreenUtils.addAppWidget(id2, 1);
					addWidget(id2, insertionIndex, true);
				}
			} else {
				for (int i = lenght - 1; i >= 0; i--) {
					if (widgets[i] != LockPatternUtils.ID_DEFAULT_STATUS_WIDGET) {
						addWidget(widgets[i], insertionIndex, true);
					}
				}
			}
		}
	}

	private int allocateIdForDefaultAppWidget(String pkn, String cls) {
		int appWidgetId;
		ComponentName defaultAppWidget = new ComponentName(pkn, cls);

		// Note: we don't support configuring the widget
		appWidgetId = mAppWidgetHost.allocateAppWidgetId();

		try {
			mAppWidgetManager.bindAppWidgetId(appWidgetId, defaultAppWidget);

		} catch (IllegalArgumentException e) {
			Log.e(TAG, "Error when trying to bind default AppWidget: " + e);
			mAppWidgetHost.deleteAppWidgetId(appWidgetId);
			appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
		}
		return appWidgetId;
	}

	private int getInsertPageIndex() {
		int i = mIndex;
		mIndex++;
		return i;
	}

	private AppWidgetHost getAppWidgetHost() {
		return mAppWidgetHost;
	}

	private boolean addWidget(int appId, int pageIndex, boolean updateDbIfFailed) {
		AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager
				.getAppWidgetInfo(appId);
		GnLog.d(TAG, "appWidgetInfo=" + appWidgetInfo);
		if (appWidgetInfo != null) {
			AppWidgetHostView view = getAppWidgetHost().createView(mContext,
					appId, appWidgetInfo);
			addWidget(view, pageIndex);
			return true;
		} else {
			if (updateDbIfFailed) {
				GnLog.d(TAG, "AppWidgetInfo for app widget id " + appId
						+ " was null, deleting");
				mAppWidgetHost.deleteAppWidgetId(appId);
				mLockScreenUtils.removeAppWidget(appId);
			}
			return false;
		}
	}

	private void addWidget(AppWidgetHostView view, int pageIndex) {
		GnLog.d(TAG, "addWidget view=" + view + ",pageIndex=" + pageIndex);
		mAppWidgetContainer.addWidget(view, pageIndex);
	}

	private void addDefaultWidgets() {
		LayoutInflater inflater = LayoutInflater.from(mContext);
		View addWidget = inflater.inflate(
				R.layout.zzzzz_gn_navil_ly_add_widget, null, false);
		mAddWidget = addWidget;
		mAppWidgetContainer.addWidget(addWidget, getInsertPageIndex());
		View addWidgetButton = addWidget
				.findViewById(R.id.zzzzz_gn_navil_id_keyguard_add_widget_view);
		addWidgetButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				launchWidgetPicker(AppWidgetManager.INVALID_APPWIDGET_ID);
			}
		});
	}

	private void addHomePage() {
		LayoutInflater inflater = LayoutInflater.from(mContext);
		View view = inflater.inflate(R.layout.zzzzz_gn_navil_ly_home_page,
				null, false);
		mAppWidgetContainer.addWidget(view, getInsertPageIndex());

	}

	private void addLeftPage() {
		LayoutInflater inflater = LayoutInflater.from(mContext);
		View view = inflater.inflate(R.layout.zzzzz_gn_navil_ly_left_page,
				null, false);
		mAppWidgetContainer.addWidget(view, getInsertPageIndex());

	}

	private void addRightpage() {
		LayoutInflater inflater = LayoutInflater.from(mContext);
		View view = inflater.inflate(R.layout.zzzzz_gn_navil_ly_right_page,
				null, false);
		mAppWidgetContainer.addWidget(view, getInsertPageIndex());

	}

	private void launchWidgetPicker(int appWidgetId) {
		Intent pickIntent = new Intent(
				AppWidgetManager.ACTION_KEYGUARD_APPWIDGET_PICK);

		pickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
		pickIntent.putExtra(AppWidgetManager.EXTRA_CUSTOM_SORT, false);
		pickIntent.putExtra(AppWidgetManager.EXTRA_CATEGORY_FILTER,
				AppWidgetProviderInfo.WIDGET_CATEGORY_KEYGUARD);

		Bundle options = new Bundle();
		options.putInt(AppWidgetManager.OPTION_APPWIDGET_HOST_CATEGORY,
				AppWidgetProviderInfo.WIDGET_CATEGORY_KEYGUARD);
		pickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_OPTIONS, options);
		pickIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
				| Intent.FLAG_ACTIVITY_SINGLE_TOP
				| Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);

		mContext.startActivity(pickIntent);
	}

	private OnClickHandler mOnClickHandler = new OnClickHandler() {
		@Override
		public boolean onClickHandler(final View view,
				final android.app.PendingIntent pendingIntent,
				final Intent fillInIntent) {
			GnLog.d(TAG, "onClickHandler");
			if (pendingIntent.isActivity()) {
				GnLog.d(TAG, "onClickHandler 1");

				try {
					// TODO: Unregister this handler if
					// PendingIntent.FLAG_ONE_SHOT?
					Context context = view.getContext();
					ActivityOptions opts = ActivityOptions
							.makeScaleUpAnimation(view, 0, 0,
									view.getMeasuredWidth(),
									view.getMeasuredHeight());
					context.startIntentSender(pendingIntent.getIntentSender(),
							fillInIntent, Intent.FLAG_ACTIVITY_NEW_TASK,
							Intent.FLAG_ACTIVITY_NEW_TASK, 0, opts.toBundle());
				} catch (IntentSender.SendIntentException e) {
					android.util.Log.e(TAG, "Cannot send pending intent: ", e);
				} catch (Exception e) {
					android.util.Log.e(TAG,
							"Cannot send pending intent due to "
									+ "unknown exception: ", e);
				}
				return true;

			} else {
				GnLog.d(TAG, "onClickHandler 2");
				return super.onClickHandler(view, pendingIntent, fillInIntent);
			}
		};
	};

/*	@Override
	protected void onFinishInflate() {
		super.onFinishInflate();

		View deleteDropTarget = findViewById(R.id.zzzzz_gn_navil_id_keyguard_widget_pager_delete_target);
		mAppWidgetContainer = (GnKeyguardWidgetPager) findViewById(R.id.zzzzz_gn_navil_id_app_widget_container);
		mAppWidgetContainer.setDeleteDropTarget(deleteDropTarget);
		mAppWidgetContainer.setMinScale(0.5f);
		mAppWidgetContainer.setCallbacks(mWidgetCallbacks);
		mAppWidgetContainer.setLockPatternUtils(mLockScreenUtils);
		mAppWidgetContainer.showInitialPageHints();
		GnNavilIndicator2 indicatot = (GnNavilIndicator2) findViewById(R.id.zzzzz_gn_navil_indicator);

		if (ENABLE_ADD_WIDGET) {
			addDefaultWidgets();
		}
		addWidgetsFromSettings();
		addLeftPage();
		addHomePage();
		addRightpage();

		if (ENABLE_ADD_WIDGET && numWidgets() >= MAX_WIDGETS) {
			mAppWidgetContainer.removeViewAt(0);
			mIsShowAddWiget = false;
		}
		mAppWidgetContainer.setCurrentPage(1);
		if (mAppWidgetContainer.getChildCount() > 0) {
			indicatot.setVisibility(View.VISIBLE);
			mAppWidgetContainer.setIndicator(indicatot);
		}

	}*/

	private int numWidgets() {
		final int childCount = mAppWidgetContainer.getChildCount();
		int widgetCount = 0;
		for (int i = 0; i < childCount; i++) {
			if (mAppWidgetContainer.isWidgetPage(i)) {
				widgetCount++;
			}
		}
		return widgetCount;
	}

	@Override
	public boolean isShowWallpaper() {
		return false;
	}

	@Override
	public boolean isFullScreen() {
		return false;
	}

	@Override
	public boolean isOwerDrawBg() {
		return false;
	}

	@Override
	public void onResume() {

	}

	@Override
	public void onPause() {

	}

	@Override
	public void cleanUp() {

	}

	private GnKeyguardWidgetPager.Callbacks mWidgetCallbacks = new GnKeyguardWidgetPager.Callbacks() {
		@Override
		public void userActivity() {
		}

		@Override
		public void onUserActivityTimeoutChanged() {
		}

		@Override
		public void onAddView(View v) {

		};

		@Override
		public void onRemoveView(View v, boolean draging) {
			GnLog.d(TAG, "mWidgetCallbacks onRemoveView");
			if (numWidgets() < MAX_WIDGETS) {
				if (!mIsShowAddWiget && !draging) {
					if (mAppWidgetContainer != null && mAddWidget != null) {
						GnLog.d(TAG, "mWidgetCallbacks onRemoveView addwidget");
						mAppWidgetContainer.addWidget(mAddWidget, 0);
						mIsShowAddWiget = true;
					}
				}
			}
		}
	};

}
